import bean.User;
import com.opensymphony.xwork2.ActionSupport;

import java.io.*;
import java.util.Vector;
import java.util.List;

import org.apache.struts2.ServletActionContext;

@SuppressWarnings("serial")
public class UserAction extends ActionSupport {
    private User user;
    private List<User> users;
    private final File file = new File(
            ServletActionContext.getServletContext().getRealPath("WEB-INF" + File.separator + "users.txt"));

    public User getUser() {
        return user;
    }

    /**
     * 接收请求，将以“user.”为前缀的参数封装至当前action的user属性中
     * @param param 封装名称以方法参数的小写非限定类名为前缀“user.”的请求参数的对象
     */
    public void setUser(User param) {
        this.user = param;
    }

    public List<User> getUsers() {
        return users;
    }

    @SuppressWarnings("unchecked")
    private void setUsers(File file) throws IOException, ClassNotFoundException {
        if (!file.exists()) {
            file.createNewFile();
        }
        FileInputStream fis = new FileInputStream(file);
        // 如果文件users.txt内容为空
        if (fis.available() == 0) {
            // 关闭文件输入流
            fis.close();
            users = new Vector<>();
            // 文件users.txt不为空
        } else {
            ObjectInputStream ois = new ObjectInputStream(fis);
            users = (List<User>) ois.readObject();
            ois.close();
            fis.close();
        }
    }

    public String addUser() {
        try {
            setUsers(file);
            if (user != null) {
                users.add(user);
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(users);
                oos.flush();
                oos.close();
                fos.close();
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    public String list() throws IOException, ClassNotFoundException {
        setUsers(file);
        return "result";
    }
}
